<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2020-05-07
 */

namespace app\api\model\v1;

use think\Db;
use think\Cache;
use think\Config;

/**
 * 微信小程序商城订单模型
 */
load_trait('controller/Jump');

class ShopOrder extends UserBase
{
    use \traits\controller\Jump;

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
        // 商城订单数据模型
        $this->shopGoodsModel = model('v1.ShopGoods');
        // 商城订单支付数据模型
        $this->shopOrderPayModel = model('v1.ShopOrderPay');
    }

    // 立即购买(商品详情页直接购买)
    public function getGoodsBuyNow($post = [])
    {
        // 检测提交的商品是否可购买
        $this->shopGoodsModel->detectionGoods($post);

        // 查询条件
        $where = [
            'aid' => $post['product_id'],
            'status' => 1,
            'is_del' => 0,
            'arcrank' => ['>=', 0]
        ];
        $isCount = Db::name('archives')->where($where)->count();
        if (!empty($isCount)) {
            // 强制删除订单创建缓存表数据
            $where = [
                'cookie_type' => 1,
                'users_id' => $this->users_id
            ];
            Db::name('shop_order_cookie')->where($where)->delete(true);

            // 对ID和订单号加密，拼装url路径
            $cookieData = [
                'users_id' => $this->users_id,
                'product_id' => $post['product_id'],
                'product_num' => $post['product_num'],
                'active_time_id' => isset($post['active_time_id']) ? $post['active_time_id'] : 0,
                'discount_active_id' => isset($post['discount_active_id']) ? $post['discount_active_id'] : 0,
            ];
            // 存在规格则执行
            if (!empty($post['spec_value_id']) && 'undefined' != $post['spec_value_id']) $cookieData['spec_value_id'] = $post['spec_value_id'];

            // 将订单缓存写入数据库
            $insert = [
                'users_id' => $this->users_id,
                'cookie_data' => serialize($cookieData),
                'cookie_type' => 1,
                'add_time' => getTime(),
                'update_time' => getTime(),
            ];
            $cookieID = Db::name('shop_order_cookie')->insertGetId($insert);
            if (!empty($cookieID)) {
                // 跳转链接
                $url = '/pages/submitOrder/submitOrder?cookieID=' . $cookieID;
                $this->success('数据正确', $url);
            } else {
                $this->error('数据异常，请再次购买');
            }
        } else {
            $this->error('该商品不存在或已下架！');
        }
    }

    // 订单列表
    public function getOrderList($dataType = 'all')
    {
        if (empty($this->users_id)) return [];

        // 筛选条件
        $where = [];
        // 订单数据类型
        switch ($dataType) {
            case 'all': // 全部
                break;
            case 'payment'; // 待付款
                $where['order_status'] = 0;
                break;
            case 'delivery'; // 待发货
                $where['order_status'] = 1;
                break;
            case 'received'; // 待收货
                $where['order_status'] = 2;
                break;
            case 'complete'; // 待评价
                $where['order_status'] = 3;
                // $where['is_comment'] = 0;
                break;
            case 'close'; // 订单关闭
                $where['order_status'] = -1;
                break; 
        }

        $where['users_id'] = $this->users_id;
        $pagesize = config('paginate.list_rows') ? config('paginate.list_rows') : 15;
        $result = Db::name('shop_order')->where($where)->order('order_id desc')->paginate($pagesize, false, ['query' => request()->param()]);
        !empty($result) && $result = $result->toArray();
        $order_ids = get_arr_column($result['data'], 'order_id');

        // 订单商品详情
        $orderGoods = [];
        $where = [
            'order_id' => ['IN', $order_ids],
            'users_id' => $this->users_id,
        ];
        $goodsList = Db::name('shop_order_details')->where($where)->order('details_id asc')->select();
        foreach ($goodsList as $value) {
            $goodsData = unserialize($value['data']);
            $value['product_attr'] = !empty($goodsData['product_attr']) ? $goodsData['product_attr'] : '';
            $value['product_spec'] = !empty($goodsData['product_spec']) ? $goodsData['product_spec'] : '';
            $value['litpic'] = $this->get_default_pic($value['litpic'], true);
            $value['product_price'] = unifyPriceHandle($value['product_price']);

            $orderGoods[$value['order_id']][] = $value;
        }

        // 订单内商品是否全部申请售后维权
        $allApplyService = [];
        foreach ($orderGoods as $key => $value) {
            $goodsTotalNum = 0;
            foreach ($value as $key_1 => $value_1) {
                if (!empty($value_1['apply_service']) && 1 === intval($value_1['apply_service'])) $goodsTotalNum++;
            }
            $allApplyService[$key] = intval($goodsTotalNum) === intval(count($value)) ? 1 : 0;
        }

        // 订单处理
        $orderStatusArr = config('global.order_status_arr');
        foreach ($result['data'] as $key => $value) {
            $value['channel_ntitle'] = '商品'; 
            $value['add_time'] = MyDate('Y-m-d H:i:s', $value['add_time']);
            // $value['order_amount_arr'] = explode('.', $value['order_amount']);
            $value['goods'] = !empty($orderGoods[$value['order_id']]) ? $orderGoods[$value['order_id']] : [];
            $value['all_apply_service'] = !empty($allApplyService[$value['order_id']]) ? $allApplyService[$value['order_id']] : 0;
            $value['order_status_text'] = !empty($orderStatusArr[$value['order_status']]) ? $orderStatusArr[$value['order_status']] : '';

            // 支付金额处理
            $value['order_total_amount'] = unifyPriceHandle($value['order_total_amount']);
            $value['shipping_fee'] = unifyPriceHandle($value['shipping_fee']);
            $value['coupon_price'] = unifyPriceHandle($value['coupon_price']);
            $value['order_amount'] = unifyPriceHandle($value['order_amount']);
            $value['pay_use_cash'] = unifyPriceHandle($value['pay_use_cash']);
            $value['pay_use_cash_arr'] = explode('.', $value['pay_use_cash']);
            $value['pay_use_balance'] = unifyPriceHandle($value['pay_use_balance']);
            $value['pay_use_scores'] = unifyPriceHandle($value['pay_use_scores']);
            $value['pay_use_scores_num'] = intval($value['pay_use_scores_num']);

            $result['data'][$key] = $value;
        }

        // 是否开启订单评价功能
        $result['config']['shop_open_comment'] = !empty($this->usersConfig['shop_open_comment']) ? intval($this->usersConfig['shop_open_comment']) : 0;
        $score = getUsersConfigData('score');
        $result['config']['score_name'] = $score['score_name'];
        return $result;
    }

    // 获取订单总数
    public function getOrderCount($users, $type = 'all')
    {
        if ($users === false) return false;

        $where = [
            'users_id' => $this->users_id,
            'order_status' => ['IN', [0, 1, 2, 3]],
        ];
        $shopOrder = Db::name('shop_order')->field('order_id, order_status')->where($where)->select();
        // 订单分类统计
        $order_ids = [];
        $payment = $delivery = $received = $complete = $uncomment = 0;
        foreach ($shopOrder as $key => $value) {
            if (0 === intval($value['order_status'])) {
                $payment++;
            } else if (1 === intval($value['order_status'])) {
                $delivery++;
            } else if (2 === intval($value['order_status'])) {
                $received++;
            } else if (3 === intval($value['order_status'])) {
                $complete++;
                array_push($order_ids, $value['order_id']);
            }
        }
        // 待评价订单数量
        $where = [
            'users_id' => $this->users_id,
            'order_id' => ['IN', $order_ids],
        ];
        $goodsList = Db::name('shop_order_details')->where($where)->order('details_id asc')->select();
        $orderGoods = !empty($goodsList) ? group_same_key($goodsList, 'order_id') : [];
        foreach ($orderGoods as $key => $value) {
            $goodsTotalNum = 0;
            foreach ($value as $key_1 => $value_1) {
                if (!empty($value_1['apply_service']) && 1 === intval($value_1['apply_service'])) $goodsTotalNum++;
            }
            if (intval($goodsTotalNum) !== intval(count($value))) $uncomment++;
        }
        return [
            'payment' => $payment,
            'delivery' => $delivery,
            'received' => $received,
            'complete' => $complete,
            'uncomment' => $uncomment,
        ];
    }

    //获取退款订单数量总数
    public function getRefoundCount($users)
    {
        $where['users_id'] = !empty($users['users_id']) ? intval($users['users_id']) : 0;
        $where['status'] = ['in', [1, 2, 4, 5, 6]];
        $count = Db::name('shop_order_service')->where($where)->count();
        return $count;
    }

    // 订单详情
    public function getOrderDetail($order_id = 0, $users_id = 0)
    {
        if (empty($this->users_id)) $this->error('请先登录');

        // 公共条件
        $where = [
            'order_id' => $order_id,
            'users_id' => $users_id,
        ];
        // 订单主表
        $result = Db::name("shop_order")->where($where)->find();
        if (empty($result)) $this->error('订单不存在！');
        // 支付金额处理
        $result['order_total_amount'] = unifyPriceHandle($result['order_total_amount']);
        $result['shipping_fee'] = unifyPriceHandle($result['shipping_fee']);
        $result['coupon_price'] = unifyPriceHandle($result['coupon_price']);
        $result['order_amount'] = unifyPriceHandle($result['order_amount']);
        $result['pay_use_cash'] = unifyPriceHandle($result['pay_use_cash']);
        $result['pay_use_cash_arr'] = explode('.', $result['pay_use_cash']);
        $result['pay_use_balance'] = unifyPriceHandle($result['pay_use_balance']);
        $result['pay_use_scores'] = unifyPriceHandle($result['pay_use_scores']);
        $result['pay_use_scores_num'] = intval($result['pay_use_scores_num']);
        // 下单时间
        $result['add_time_text'] = MyDate('Y-m-d H:i:s', $result['add_time']);
        // 付款时间
        $result['pay_time_text'] = !empty($result['pay_time']) ? MyDate('Y-m-d H:i:s', $result['pay_time']) : 0;
        // 付款方式
        $result['pay_name_text'] = !empty($result['pay_time']) ? Config::get('global.pay_method_arr')[$result['pay_name']] : '';
        // 发货时间
        $result['express_time_text'] = !empty($result['express_time']) ? MyDate('Y-m-d H:i:s', $result['express_time']) : 0;
        // 收货时间
        $result['confirm_time_text'] = !empty($result['confirm_time']) ? MyDate('Y-m-d H:i:s', $result['confirm_time']) : 0;
        // 收货地址
        $result['province_text'] = get_province_name($result['province']);
        $result['city_text']     = get_city_name($result['city']);
        $result['district_text'] = get_area_name($result['district']);
        $result['all_address'] = $result['province_text'] . $result['city_text'] . $result['district_text'] . $result['address'];
        // 获取订单状态
        $orderStatusArr = config('global.order_status_arr');
        $result['order_status_text'] = !empty($orderStatusArr[$result['order_status']]) ? $orderStatusArr[$result['order_status']] : '';
        // 订单明细表
        $result['goods'] = Db::name("shop_order_details")->order('details_id asc')->where($where)->select();

        // 订单内商品是否全部申请售后维权
        $goodsTotalNum = 0;
        foreach ($result['goods'] as $value) {
            if (!empty($value['apply_service']) && 1 === intval($value['apply_service'])) $goodsTotalNum++;
        }
        $result['all_apply_service'] = intval($goodsTotalNum) === intval(count($result['goods'])) ? 1 : 0;
        
        //虚拟商品拼接回复
        $virtual_delivery = '';
        // 虚拟发货
        $virtual_delivery_status = false;
        // 商品处理
        foreach ($result['goods'] as $key => $value) {
            $result['prom_type']  = $value['prom_type'];
            //虚拟需要自动发货的商品卖家回复拼接
            if ($value['prom_type'] == 2 && 2 <= intval($result['order_status'])) {
                $virtual_delivery_status = true;
                //查询商品名称
                $product_title = Db::name('archives')->where('aid', $value['product_id'])->getField('title');
                //查网盘信息
                $netdisk = Db::name("product_netdisk")->where('aid', $value['product_id'])->find();
                if ($netdisk) {
                    $virtual_delivery .= "商品标题：" . $product_title . "</br>";
                    $virtual_delivery .= "网盘地址：" . $netdisk['netdisk_url'] . "</br>";
                    if (!empty($netdisk['netdisk_pwd'])) {
                        $virtual_delivery .= "提取码：" . $netdisk['netdisk_pwd'] . "</br>";
                    }
                    if (!empty($netdisk['unzip_pwd'])) {
                        $virtual_delivery .= "解压密码：" . $netdisk['unzip_pwd'] . "</br>";
                    }
                    $virtual_delivery .= "--------------------";
                }
                $result['netdisk'] =  $netdisk;
            }
            else if ($value['prom_type'] == 3 && 2 <= intval($result['order_status'])) {
                $virtual_delivery_status = true;
                //查询商品名称
                $product_title = Db::name('archives')->where('aid', $value['product_id'])->getField('title');
                //查网盘信息
                $netdisk = Db::name("product_netdisk")->where('aid', $value['product_id'])->find();
                if ($netdisk) {
                    $virtual_delivery .= "商品标题：" . $product_title . "</br>";
                    $virtual_delivery .= "文本内容：" . $netdisk['text_content'] . "</br>";
                    $virtual_delivery .= "--------------------";
                }
                $result['netdisk'] =  $netdisk;
            }
            else if ($value['prom_type'] == 1) {
                //查询商品名称
                if (!empty($result['virtual_delivery'])) {
                    $product_title    = Db::name('archives')->where('aid', $value['product_id'])->getField('title');
                    $virtual_delivery .= "商品标题：" . $product_title . "</br>";
                    $virtual_delivery .= filter_line_return($result['virtual_delivery'], '</br>') . "</br>";
                    $virtual_delivery .= "--------------------";
                }
            }
            $result['virtual_delivery_status'] = $virtual_delivery_status;

            // 图片处理
            $value['litpic'] = $this->get_default_pic($value['litpic'], true);
            // 商品小计
            $value['product_price'] = unifyPriceHandle($value['product_price']);
            $value['subtotal'] = $value['product_price'] * $value['num'];
            $value['subtotal'] = unifyPriceHandle($value['subtotal']);
            // 商品属性处理
            $goodsData = unserialize($value['data']);
            $value['product_attr'] = !empty($goodsData['product_attr']) ? $goodsData['product_attr'] : '';
            $value['product_spec'] = !empty($goodsData['product_spec']) ? $goodsData['product_spec'] : '';
            $result['goods'][$key] = $value;
        }

        return $result;
    }

    // 获取商品信息进行展示
    public function getGoodsBuyPage($cookieID = 0, $userInfo = [], $return = false, $useID = 0, $useScorePay = 0, $useBalancePay = 0)
    {
        if (empty($this->users_id)) $this->error('请先登录');
        // 单个商品立即购买时缓存，购物车提交时为空
        $cacheData = [];
        if (!empty($cookieID)) {
            $where = [
                'cookie_type' => 1,
                'cookie_id' => $cookieID,
                'users_id' => $this->users_id
            ];
            $cacheData = Db::name('shop_order_cookie')->where($where)->getField('cookie_data');
            $cacheData = !empty($cacheData) ? unserialize($cacheData) : [];
        }

        // 查询商品信息列表(购物车商品 或 立即购买商品)
        $goodsList = $this->shopGoodsModel->getGoodsBuyList($cacheData, $this->users_id);
        if (empty($goodsList)) $this->error('没有购买的商品，请重新下单');

        // 会员收货地址
        $address = Db::name('shop_address')->where('users_id', $this->users_id)->order('is_default desc')->find();
        // 查询运费模板运费金额
        $shippingFee = 0;
        // 是否提示有商品不在配送区域内
        $allowSubmit = 1;
        if (!empty($address)) {
            // 根据收货地址的城市ID获取本次订单运费
            $resultData = $this->shopGoodsModel->getGoodsShippingFee($goodsList, $address);
            if (!empty($resultData)) {
                $goodsList = !empty($resultData['goodsList']) ? $resultData['goodsList'] : [];
                $allowSubmit = !empty($resultData['allowSubmit']) ? intval($resultData['allowSubmit']) : 0;
                $shippingFee = !empty($resultData['shippingFee']) ? floatval($resultData['shippingFee']) : 0;
                // 如果这个会员所属的等级权益中有包邮则执行
                $shippingFee = !empty($userInfo['postage']) ? 0 : $shippingFee;
            }
        }

        // 会员折扣
        $usersDiscount = !empty($userInfo['level_discount']) ? strval($userInfo['level_discount']) / strval(100) : 0;
        // 秒杀商品没有会员折扣
        if (!empty($cacheData['active_time_id'])) $usersDiscount = 0;

        // 商品规格/折扣数据处理
        $goodsList = $this->shopGoodsModel->getGoodsHandleResult($goodsList, $usersDiscount);
        if (empty($goodsList)) $this->error('商品库存不足或已过期');

        // 全局参数预设
        $globalParam = $this->getGlobalParam($allowSubmit, $shippingFee);

        // 商品数据整合处理
        $result = $this->shopGoodsModel->getGoodsPriceHandle($goodsList, $globalParam);
        $goodsList = !empty($result['goodsList']) ? $result['goodsList'] : [];
        $globalParam = !empty($result['globalParam']) ? $result['globalParam'] : [];

        // 获取会员的商品优惠券
        $goodsCoupon = $this->shopGoodsModel->getGoodsCoupon($goodsList, $this->users_id);

        // 提交订单时执行
        $useFindCoupon = [];
        if (!empty($return) && isset($useID)) {
            // 使用指定优惠券
            foreach ($goodsCoupon['useAllCoupon'] as $key => $value) {
                if (intval($value['use_id']) === intval($useID)) {
                    $useFindCoupon = $value;
                    break;
                }
            }
        } else {
            // 默认使用的优惠券
            $useFindCoupon = !empty($goodsCoupon['useAllCoupon'][0]) ? $goodsCoupon['useAllCoupon'][0] : [];
        }
        // 全局参数处理
        $globalParam = $this->getGlobalParamHandle($globalParam, $useFindCoupon);

        // 默认地址
        if (!empty($address)) {
            $address['region']['shipping_fee'] = $shippingFee;
            $address['region']['province'] = $this->getRegionName($address['province']);
            $address['region']['city']     = $this->getRegionName($address['city']);
            $address['region']['district'] = $this->getRegionName($address['district']);
            $address['region']['detail'] = !empty($address['address']) ? strval($address['address']) : '';
            $address['address_all'] = $address['region']['province'] . $address['region']['city'] . $address['region']['district'] . $address['address'];
        }

        // 追加一个不使用优惠券选项
        $goodsCoupon['useAllCoupon'] = array_merge([['use_id'=>0, 'coupon_name'=>'不使用优惠券']], $goodsCoupon['useAllCoupon']);

        // 积分抵扣逻辑
        $globalParam['usersScores'] = !empty($userInfo['scores']) ? intval($userInfo['scores']) : 0;
        $globalParam = $this->getUseScoreHandle($globalParam, $useScorePay);

        // 余额抵扣逻辑
        $globalParam['usersMoney'] = !empty($userInfo['users_money']) ? unifyPriceHandle($userInfo['users_money']) : 0;
        $globalParam = $this->getUseBalanceHandle($globalParam, $useBalancePay);

        // 数据返回
        $resultData = [
            'address' => !empty($address) ? $address : [],
            'userInfo' => !empty($userInfo) ? $userInfo : [],
            'goodsList' => !empty($goodsList) ? $goodsList : [],
            'globalParam' => !empty($globalParam) ? $globalParam : [],
            'goodsCoupon' => !empty($goodsCoupon) ? $goodsCoupon : [],
            'useFindCoupon' => !empty($useFindCoupon) ? $useFindCoupon : [],
        ];
        if (!empty($return)) {
            return $resultData;
        } else {
            $this->success('数据正确', null, $resultData);
        }
    }

    // 地址ID换取地址名称
    private function getRegionName($id = 1)
    {
        $name = Db::name('region')->where('id', $id)->getField('name');
        return $name;
    }

    // 组装订单流程所需全局信息
    private function getGlobalParam($allowSubmit = 1, $shippingFee = 0)
    {
        $globalParam = [
            // 订单扣除或恢复库存类型，0=下单减库存，1=付款减库存
            'orderStockType' => !empty($this->usersConfig['goods_stock_deduct']) ? intval($this->usersConfig['goods_stock_deduct']) : 0,
            // 商品总数
            'orderTotalNum' => 0,
            // 商品总额
            'orderTotalAmount' => 0,
            // 订单运费
            'shippingFee' => unifyPriceHandle($shippingFee),
            // 优惠券金额
            'couponPrice' => 0,
            // 支付总额
            'orderAmount' => 0,
            // 订单使用现金支付部分(微信支付、支付宝支付)
            'payUseCash' => 0,
            'payUseCashArr' => [],
            // 订单使用余额支付部分(买家余额)
            'payUseBalance' => 0,
            // 订单使用积分支付部分(积分转化的抵扣额)
            'payUseScores' => 0,
            // 订单使用积分支付部分(积分数，订单商品维权时需要)
            'payUseScoresNum' => 0,
            // 是否提示有商品不在配送区域内
            'allowSubmit' => intval($allowSubmit),
            // 积分设置
            'scoreDeductionStatus' => !empty($this->usersConfig['score_deduction_status']) ? intval($this->usersConfig['score_deduction_status']) : 0,
            'scoreDeductionType' => !empty($this->usersConfig['score_deduction_type']) ? intval($this->usersConfig['score_deduction_type']) : 0,
            'scoreDeductionScore' => !empty($this->usersConfig['score_deduction_score']) ? intval($this->usersConfig['score_deduction_score']) : 0,
            'scoreDeductionMaxScore' => !empty($this->usersConfig['score_deduction_max_score']) ? intval($this->usersConfig['score_deduction_max_score']) : 0,
            'scoreDeductionMaxPercent' => !empty($this->usersConfig['score_deduction_max_percent']) ? intval($this->usersConfig['score_deduction_max_percent']) : 0,
        ];

        return $globalParam;
    }

    // 全局参数处理
    private function getGlobalParamHandle($globalParam = [], $useFindCoupon = [])
    {
        // 获取优惠券金额
        $globalParam['couponPrice'] = !empty($useFindCoupon['coupon_price']) ? floatval($useFindCoupon['coupon_price']) : 0;
        // 最终支付总金额 = 订单商品总额 + 订单运费
        $globalParam['orderAmount'] = unifyPriceHandle(floatval($globalParam['orderTotalAmount']) + floatval($globalParam['shippingFee']));
        // 最终支付总金额 = 最终支付总金额 - 优惠券金额
        $globalParam['orderAmount'] = unifyPriceHandle(floatval($globalParam['orderAmount']) - floatval($globalParam['couponPrice']));
        // 使用现金支付部分(微信支付、支付宝支付)
        $globalParam['payUseCash'] = $globalParam['orderAmount'];
        // 支付金额处理
        $globalParam['payUseCashArr'] = explode('.', $globalParam['payUseCash']);

        return $globalParam;
    }

    // 使用积分抵扣逻辑处理
    private function getUseScoreHandle($globalParam = [], $useScorePay = 0)
    {
        // 抵扣1元需要多少积分
        // $globalParam['scoreDeductionScore'] = !empty($this->usersConfig['score_deduction_score']) ? intval($this->usersConfig['score_deduction_score']) : 0;

        // 使用积分的类型：0=最多可用积分抵消单笔订单金额的百分比 1=单笔订单最多可使用多少积分抵扣
        // $globalParam['scoreDeductionType'] = !empty($this->usersConfig['score_deduction_type']) ? intval($this->usersConfig['score_deduction_type']) : 0;
        if (!empty($globalParam['scoreDeductionType']) && 1 === intval($globalParam['scoreDeductionType'])) {
            // 单笔订单最多可使用多少积分抵扣
            // $globalParam['scoreDeductionMaxScore'] = !empty($this->usersConfig['score_deduction_max_score']) ? intval($this->usersConfig['score_deduction_max_score']) : 0;
            // 最多可使用多少积分
            $payUseScoresNum = intval($globalParam['usersScores']) > intval($globalParam['scoreDeductionMaxScore']) ? $globalParam['scoreDeductionMaxScore'] : $globalParam['usersScores'];
            // 积分可抵扣多少金额
            $payUseScores = intval($payUseScoresNum) / intval($globalParam['scoreDeductionScore']);
            // 如果抵扣积分不为整数则再次重新计算
            if (!is_int($payUseScores)) {
                $payUseScores = intval(explode('.', $payUseScores)[0]);
                $payUseScoresNum = intval($payUseScores) * intval($globalParam['scoreDeductionScore']);
            }
            if (floatval($payUseScores) > floatval($globalParam['payUseCash'])) {
                $payUseScores = unifyPriceHandle($globalParam['payUseCash']);
                $payUseScoresNum = intval(ceil(floatval($payUseScores) * floatval($globalParam['scoreDeductionScore'])));
            }
        } else {
            // 最多可用积分抵消单笔订单金额的百分比
            // $globalParam['scoreDeductionMaxPercent'] = !empty($this->usersConfig['score_deduction_max_percent']) ? intval($this->usersConfig['score_deduction_max_percent']) : 0;
            // 计算积分最多可抵扣订单的多少金额
            $payUseScores = ceil(floatval($globalParam['payUseCash']) * floatval(intval($globalParam['scoreDeductionMaxPercent']) / 100));
            // 计算抵扣需要多少个积分
            $payUseScoresNum = intval($payUseScores) * intval($globalParam['scoreDeductionScore']);
            // 计算用户是否有足够的积分进行抵扣，如果不够则执行
            if (intval($globalParam['usersScores']) < intval($payUseScoresNum)) {
                // 将用户的积分覆盖订单最大使用积分
                $payUseScoresNum = $globalParam['usersScores'];
                // 重新积分用户可抵扣金额和使用积分
                $payUseScores = intval($payUseScoresNum) / intval($globalParam['scoreDeductionScore']);
                // 如果抵扣积分不为整数则再次重新计算
                if (!is_int($payUseScores)) {
                    $payUseScores = intval(explode('.', $payUseScores)[0]);
                    $payUseScoresNum = intval($payUseScores) * intval($globalParam['scoreDeductionScore']);
                }
            }
        }
        $globalParam['useScorePay'] = intval($useScorePay);
        $globalParam['payUseScores'] = !empty($payUseScores) ? floatval($payUseScores) : 0;
        $globalParam['payUseScoresNum'] = !empty($payUseScoresNum) ? intval($payUseScoresNum) : 0;

        // 是否计算更新订单商品总额和订单支付金额
        if (1 === intval($useScorePay)) {
            $globalParam['payUseCash'] = floatval($globalParam['payUseCash']) - floatval($globalParam['payUseScores']);
        }

        // dump($globalParam);exit;
        return $globalParam;
    }

    // 使用余额抵扣逻辑处理
    private function getUseBalanceHandle($globalParam = [], $useBalancePay = 0)
    {
        $globalParam['useBalancePay'] = intval($useBalancePay);
        $globalParam['payUseBalance'] = 0;
        if (floatval($globalParam['usersMoney']) > $globalParam['payUseCash']) {
            $globalParam['payUseBalance'] = unifyPriceHandle($globalParam['payUseCash']);
            if (1 === intval($useBalancePay)) $globalParam['payUseCash'] = 0;
        } else {
            $globalParam['payUseBalance'] = unifyPriceHandle($globalParam['usersMoney']);
            if (1 === intval($useBalancePay)) $globalParam['payUseCash'] = floatval($globalParam['payUseCash']) - floatval($globalParam['payUseBalance']);
        }

        // dump($globalParam);exit;
        return $globalParam;
    }

    // 订单结算
    public function getOrderPay($post = [], $userInfo = [])
    {
        // 基础判断
        if (empty($this->users_id)) $this->error('请先登录');
        if (empty($post['addrID']) || $post['addrID'] == 'undefined') $this->error('请添加收货地址');

        // 获取订单数据
        $result = $this->getGoodsBuyPage($post['cookieID'], $userInfo, true, $post['useID'], $post['useScorePay'], $post['useBalancePay']);
        $address = !empty($result['address']) ? $result['address'] : [];
        $goodsList = !empty($result['goodsList']) ? $result['goodsList'] : [];
        $globalParam = !empty($result['globalParam']) ? $result['globalParam'] : [];
        $useFindCoupon = !empty($result['useFindCoupon']) ? $result['useFindCoupon'] : [];

        // 是否有足够的余额进行支付
        // if (1 === intval($post['useUsersMoney'])) {
        //     $usersMoney = Db::name('users')->where('users_id', $this->users_id)->getField('users_money');
        //     if (floatval($globalParam['orderAmount']) > floatval($usersMoney)) $this->error('您的余额不足，支付失败');
        // }

        // 添加到订单主表
        $times = getTime();
        $insert = [
            'order_code'         => date('Ymd') . $times . rand(10, 100),
            'users_id'           => $this->users_id,
            'order_status'       => 0,
            'order_terminal'     => 3,
            'order_stock_type'   => !empty($globalParam['orderStockType']) ? intval($globalParam['orderStockType']) : 0,
            'order_total_num'    => !empty($globalParam['orderTotalNum']) ? floatval($globalParam['orderTotalNum']) : 0,
            'order_total_amount' => !empty($globalParam['orderTotalAmount']) ? floatval($globalParam['orderTotalAmount']) : 0,
            'shipping_fee'       => !empty($globalParam['shippingFee']) ? floatval($globalParam['shippingFee']) : 0,
            'coupon_price'       => 0,
            'order_amount'       => !empty($globalParam['orderAmount']) ? floatval($globalParam['orderAmount']) : 0,
            'pay_use_cash'       => !empty($globalParam['payUseCash']) ? floatval($globalParam['payUseCash']) : 0,
            'pay_use_balance'    => !empty($globalParam['payUseBalance']) && 1 === intval($post['useBalancePay']) ? floatval($globalParam['payUseBalance']) : 0,
            'pay_use_scores'     => !empty($globalParam['payUseScores']) && 1 === intval($post['useScorePay']) ? floatval($globalParam['payUseScores']) : 0,
            'pay_use_scores_num' => !empty($globalParam['payUseScoresNum']) && 1 === intval($post['useScorePay']) ? intval($globalParam['payUseScoresNum']) : 0,
            'payment_method'     => 0,
            'pay_time'           => 0,
            'pay_name'           => !empty($globalParam['payUseCash']) ? 'wechat' : 'balance',
            'wechat_pay_type'    => !empty($globalParam['payUseCash']) ? 'WeChatH5' : '',
            'pay_details'        => '',
            'prom_type'          => 0,
            'order_source'       => isset($post['order_source']) ? $post['order_source'] : 10,
            'order_source_id'    => isset($post['order_source_id']) ? $post['order_source_id'] : 0,
            'virtual_delivery'   => '',
            'admin_note'         => '',
            'user_note'          => !empty($post['remark']) ? $post['remark'] : '',
            'add_time'           => $times,
        ];
        // 存在收货地址则追加合并到主表数组
        if (!empty($address)) {
            $insert['city'] = !empty($address['city']) ? intval($address['city']) : '';
            $insert['mobile'] = !empty($address['mobile']) ? strval($address['mobile']) : '';
            $insert['address'] = !empty($address['address']) ? strval($address['address']) : '';
            $insert['province'] = !empty($address['province']) ? intval($address['province']) : '';
            $insert['district'] = !empty($address['district']) ? intval($address['district']) : '';
            $insert['consignee'] = !empty($address['consignee']) ? strval($address['consignee']) : '';
        }
        // 使用优惠券则追加优惠券信息
        if (!empty($useFindCoupon)) {
            $insert['use_id'] = !empty($useFindCoupon['use_id']) ? intval($useFindCoupon['use_id']) : 0;
            $insert['coupon_id'] = !empty($useFindCoupon['coupon_id']) ? intval($useFindCoupon['coupon_id']) : 0;
            $insert['coupon_price'] = !empty($useFindCoupon['coupon_price']) ? floatval($useFindCoupon['coupon_price']) : 0;
        }
        // 获取消费获得积分数据
        $insert['obtain_scores'] = getConsumObtainScores($insert, $this->usersConfig, true);
        $insert['is_obtain_scores'] = !empty($insert['obtain_scores']) ? 0 : 1;

        // 添加订单
        $orderID = Db::name('shop_order')->insertGetId($insert);
        if (!empty($orderID)) {
            // 追加自增ID
            $insert['order_id'] = $orderID;

            // 查询商品属性
            $aids = get_arr_column($goodsList, 'aid');
            $where = [
                'aid' => ['IN', $aids]
            ];
            $field = 'aid, attr_value';
            $goodsAllAttr = Db::name('shop_product_attr')->field($field)->where($where)->select();
            $goodsAllAttr = !empty($goodsAllAttr) ? group_same_key($goodsAllAttr, 'aid') : [];

            // 商品循环处理
            $cartIds = $upSpecValue = [];
            foreach ($goodsList as $key => $value) {
                // 商品属性处理
                $productAttr = !empty($goodsAllAttr[$value['aid']]) ? $goodsAllAttr[$value['aid']] : [];
                $productAttr = !empty($productAttr) ? implode('；', get_arr_column($productAttr, 'attr_value')) : '';
                // 商品规格、商品属性
                $paramData = [
                    // 商品属性
                    'product_attr' => htmlspecialchars($productAttr),
                    // 商品规格
                    'product_spec' => htmlspecialchars($value['product_spec']),
                ];
                // 订单副表添加数组
                $insertDetails[] = [
                    'order_id'      => $orderID,
                    'users_id'      => $this->users_id,
                    'product_id'    => intval($value['aid']),
                    'spec_value_id' => strval($value['spec_value_id']),
                    'product_name'  => strval($value['title']),
                    'num'           => intval($value['product_num']),
                    'data'          => serialize($paramData),
                    'product_price' => floatval($value['users_price']),
                    'prom_type'     => 0,
                    'litpic'        => strval($value['litpic']),
                    'add_time'      => $times,
                ];

                // 处理购物车ID
                if (!empty($post['cartSubmit'])) array_push($cartIds, $value['cart_id']);

                // 商品库存处理
                $upSpecValue[] = [
                    'aid' => $value['aid'],
                    'value_id' => $value['value_id'],
                    'quantity' => $value['product_num'],
                    'spec_value_id' => $value['spec_value_id'],
                    'order_source' => isset($post['order_source']) ? $post['order_source'] : 10,
                    'order_source_id' => isset($post['order_source_id']) ? $post['order_source_id'] : 0,
                ];
            }
            $result = Db::name('shop_order_details')->insertAll($insertDetails);
            if (!empty($result)) {
                // 清理购物车中已下单的ID
                if (!empty($cartIds)) Db::name('shop_cart')->where('cart_id', 'IN', $cartIds)->delete();

                // 商品库存、销量处理（下单减库存）
                if (isset($insert['order_stock_type']) && 0 === intval($insert['order_stock_type'])) {
                    $this->shopGoodsModel->goodsStockDeduct($upSpecValue);
                }

                // 添加订单操作记录
                AddOrderAction($orderID, $this->users_id);

                // 扣除用于订单支付的积分和余额
                $this->shopOrderPayModel->handleOrderBalanceScorePay($insert);

                // 锁定优惠券
                if (!empty($useFindCoupon['use_id']) && !empty($useFindCoupon['coupon_id'])) {
                    $where = [
                        'use_status' => 0,
                        'users_id' => $this->users_id,
                        'use_id' => intval($useFindCoupon['use_id']),
                        'coupon_id' => intval($useFindCoupon['coupon_id']),
                    ];
                    $update = [
                        'use_status' => 1,
                        'use_time' => getTime(),
                        'update_time' => getTime()
                    ];
                    Db::name('shop_coupon_use')->where($where)->update($update);
                }

                // 是否是真实用户 0-否 1-是
                eyou_set_is_real($this->users_id);

                // 订单选择微信支付
                if (floatval($insert['pay_use_cash']) > floatval(0)) {
                    // 订单微信支付接口
                    $weChatPay = $this->shopOrderPayModel->getWechatAppletsPay($userInfo['openid'], $insert['order_code'], $insert['pay_use_cash']);
                    // $weChatPay = $this->shopOrderPayModel->getWechatAppletsPay($userInfo['openid'], $insert['order_code'], '0.01');
                    $result = [
                        'weChatPay' => $weChatPay,
                        'orderData' => [
                            'order_id' => $orderID,
                            'order_code' => $insert['order_code'],
                            'pay_use_cash' => $insert['pay_use_cash'],
                        ]
                    ];

                    // 已开启的微信订阅消息模板
                    $where = [
                        'send_scene' => ['IN', [5, 6]],
                        'template_code' => ['gt', 0],
                        'is_open' => 1,
                    ];
                    $tmplData = Db::name('weixin_template')->where($where)->order('send_scene asc')->getAllWithIndex('template_id');
                    $result['tmplData'] = $tmplData;

                    $this->success('正在支付', null, $result);
                }
                // 积分+余额抵扣足够，不需要其他支付
                else if (floatval($insert['pay_use_cash']) <= floatval(0)) {
                    // 订单积分余额支付处理
                    $this->shopOrderPayModel->orderBalancePayHandle($insert);
                }
            } else if (!empty($orderID) && empty($result)) {
                // 订单详情添加失败则删除已添加的订单主表数据
                Db::name('shop_order')->delete($orderID);
                $this->error('订单生成失败，商品数据有误！');
            }
        }
        $this->error('订单生成失败，商品数据有误！');
    }

    // 用于订单列表和订单详情页直接支付
    public function getOrderDirectPay($post = [], $userInfo = [])
    {
        $where = [
            'order_id' => $post['order_id'],
            'order_code' => $post['order_code'],
            'users_id' => $userInfo['users_id'],
        ];
        $field = 'order_status, order_amount';
        $shopOrder = Db::name('shop_order')->where($where)->field($field)->find();
        if (!empty($shopOrder)) {
            if (0 == $shopOrder['order_status']) {
                // 订单微信支付接口
                $weChatPay = $this->shopOrderPayModel->getWechatAppletsPay($userInfo['openid'], $post['order_code'], $shopOrder['order_amount']);
                // $weChatPay = $this->shopOrderPayModel->getWechatAppletsPay($userInfo['openid'], $post['order_code'], '0.01');
                $result = [
                    'weChatPay' => $weChatPay,
                    'orderData' => [
                        'order_id' => $post['order_id'],
                        'order_code' => $post['order_code']
                    ]
                ];
                $this->success('正在支付', '/pages/order/index', $result);
            } else if (in_array($shopOrder['order_status'], [1, 2, 3])) {
                $this->success('订单已支付');
            } else if ($shopOrder['order_status'] == 4) {
                $this->success('订单已过期');
            } else if ($shopOrder['order_status'] == -1) {
                $this->success('订单已关闭');
            }
        }
        $this->error('订单不存在');
    }

    // 微信小程序支付后续处理
    public function getOrderPayHandle($post = [], $userInfo = [], $notify = false)
    {
        $orderID = !empty($post['order_id']) ? intval($post['order_id']) : 0;
        $orderCode = !empty($post['order_code']) ? strval($post['order_code']) : '';
        $openID = !empty($userInfo['openid']) ? strval($userInfo['openid']) : '';
        $usersID = !empty($userInfo['users_id']) ? intval($userInfo['users_id']) : 0;

        // 存在订单ID和订单编号则执行
        if (!empty($orderID) && !empty($orderCode)) {
            // 查询订单信息
            $where = [
                'users_id' => $usersID,
                'order_id' => $orderID,
                'order_code' => $orderCode,
            ];
            $shopOrder = Db::name('shop_order')->where($where)->find();
            if (empty($shopOrder)) {
                $this->error('无效订单！');
            } else if (0 < $shopOrder['order_status']) {
                // 订单已支付
                if ($notify === true) { // 异步
                    return [
                        'code' => 1,
                        'msg'  => 'ok',
                    ];
                } else { // 同步
                    $this->success('支付完成', '/pages/order/index');
                }
            }

            // 查询订单在微信官方是否已真实完成支付
            $resultData = $this->shopOrderPayModel->getWechatPayResult($openID, $shopOrder['order_code']);

            // 返回状态
            $returnCode = !empty($resultData['return_code']) && 'SUCCESS' == $resultData['return_code'] ? $resultData['return_code'] : '';
            $resultCode = !empty($resultData['result_code']) && 'SUCCESS' == $resultData['result_code'] ? $resultData['result_code'] : '';
            $tradeState = !empty($resultData['trade_state']) && 'SUCCESS' == $resultData['trade_state'] ? $resultData['trade_state'] : '';

            // 订单已支付，处理订单流程
            if (!empty($returnCode) && !empty($resultCode) && !empty($tradeState)) {
                $times = getTime();
                $where = [
                    'order_id' => $orderID,
                    'users_id' => $usersID
                ];
                $update = [
                    'order_status' => 1,
                    'pay_details'  => serialize($resultData),
                    'pay_time'     => $times,
                    'update_time'  => $times
                ];
                $resultID = Db::name('shop_order')->where($where)->update($update);
                if (!empty($resultID)) {

                    // 商品库存、销量处理（付款减库存）
                    if (isset($shopOrder['order_stock_type']) && 1 === intval($shopOrder['order_stock_type'])) {
                        $upSpecValue = [];
                        $goodsList = Db::name('shop_order_details')->alias('a')
                            ->field('a.product_id, a.num, b.value_id')
                            ->join('__PRODUCT_SPEC_VALUE__ b', 'a.spec_value_id = b.spec_value_id and a.product_id = b.aid', 'LEFT')
                            ->where(['order_id'=>$shopOrder['order_id']])
                            ->select();
                        foreach ($goodsList as $key => $value) {
                            $upSpecValue[] = [
                                'aid' => $value['product_id'],
                                'value_id' => intval($value['value_id']),
                                'quantity' => $value['num'],
                            ];
                        }
                        model('v1.ShopGoods')->goodsStockDeduct($upSpecValue);
                    }
                    
                    // 添加订单操作记录
                    AddOrderAction($orderID, $usersID, 0, 1, 0, 1, '支付成功！', '使用微信小程序完成支付！');

                    // 订单支付完成
                    if ($notify === true) { // 异步
                        return [
                            'code' => 1,
                            'msg'  => 'ok',
                        ];
                    } else { // 同步
                        // 统计销售额
                        eyou_statistics_data(2);
                        eyou_statistics_data(3, $shopOrder['pay_use_cash']);

                        // 订单支付通知
                        $params = [
                            'users_id' => $usersID,
                            'result_id' => $orderID,
                        ];
                        eyou_send_notice(5, $params, ['seller']);

                        $this->success('支付完成', '/pages/order/index');
                    }
                }
            }
        }
    }

    // 取消订单
    public function cancelOrder($param = [])
    {
        $times = getTime();
        // 更新条件
        $where = [
            'order_id' => intval($param['order_id']),
            'users_id' => intval($this->users_id),
        ];
        // 更新数据
        $update = [
            'order_status' => -1,
            'update_time'  => $times,
        ];
        // 更新订单主表
        $result = Db::name('shop_order')->where($where)->update($update);
        if (!empty($result)) {
            // 还原优惠券
            $shopOrder = Db::name('shop_order')->where($where)->find();
            if (!empty($shopOrder['use_id'])) {
                $where = [
                    'use_id' => $shopOrder['use_id']
                ];
                $couponUse = Db::name('shop_coupon_use')->where($where)->find();
                if (!empty($couponUse)) {
                    $where = [
                        'users_id' => $this->users_id,
                        'use_id' => $shopOrder['use_id']
                    ];
                    $update = [
                        'use_time' => 0,
                        'update_time' => $times
                    ];
                    if ($couponUse['start_time'] <= $times && $couponUse['end_time'] >= $times) {
                        $update['use_status'] = 0;
                    } else {
                        $update['use_status'] = 2;
                    }
                    Db::name('shop_coupon_use')->where($where)->update($update);
                }
            }

            // 恢复用于订单支付的积分和余额
            $this->shopOrderPayModel->handleOrderBalanceScorePay($shopOrder, 'restore');

            // 商品库存恢复
            if (isset($shopOrder['order_stock_type']) && 0 === intval($shopOrder['order_stock_type'])) {
                $this->shopGoodsModel->goodsStockRestore($param['order_id'], $this->users_id);
            }

            // 添加订单操作记录
            AddOrderAction($param['order_id'], $this->users_id, 0, 0, 0, 0, '订单取消！', '关闭订单！');
            $this->success('订单取消成功！');
        }
    }

    // 订单提醒发货
    public function remindOrderSend($param = [])
    {
        // 添加订单操作记录
        AddOrderAction(intval($param['order_id']), intval($this->users_id), 0, 1, 0, 1, '提醒成功！', '提醒商家及时发货！');
        $this->success('提醒成功');
    }

    // 确认收货
    public function confirmOrder($param = [])
    {
        // 更新条件
        $where = [
            'order_id' => intval($param['order_id']),
            'users_id' => intval($this->users_id),
        ];
        // 更新数据
        $update = [
            'order_status' => 3,
            'confirm_time' => getTime(),
            'update_time'  => getTime(),
        ];
        // 更新订单主表
        $return = Db::name('shop_order')->where($where)->update($update);
        if (!empty($return)) {
            // 更新数据
            $update = [
                'update_time' => getTime(),
            ];
            // 更新订单明细表
            Db::name('shop_order_details')->where($where)->update($update);
            // 添加订单操作记录
            AddOrderAction(intval($param['order_id']), intval($this->users_id), 0, 3, 1, 1, '确认收货！', '已确认收到货物，订单完成！');
            $this->success('会员确认收货');
        } else {
            $this->error('订单号错误');
        }
    }

    // 订单再次购买
    public function againBuyOrder($param = [])
    {
        // 添加购物车商品
        $times = getTime();
        $where = [
            'order_id' => intval($param['order_id']),
            'users_id' => intval($this->users_id),
        ];
        $field = 'users_id, product_id, spec_value_id, product_name, litpic as product_img, num as product_num, data as product_data';
        $orderDetails = Db::name('shop_order_details')->field($field)->where($where)->select();
        if (empty($orderDetails)) $this->error('订单没有商品');

        // 检测是否存在不能加入购物车的商品
        $product_ids = $spec_value_ids = [];
        if (empty($param['goods_id'])) {
            // 检测异常商品
            $this->shopGoodsModel->detectAbnormalGoods($orderDetails);
        } else {
            $abnormalGoodsID = !empty($param['goods_id']) ? json_decode(htmlspecialchars_decode($param['goods_id']), true) : [];
            $product_ids = !empty($abnormalGoodsID) ? $this->shopGoodsModel->getArraySpecifyColumn($abnormalGoodsID, 'product_id') : [];
            $spec_value_ids = !empty($abnormalGoodsID) ? $this->shopGoodsModel->getArraySpecifyColumn($abnormalGoodsID, 'spec_value_id') : [];
        }

        // 加入购物车
        $saveData = [];
        // 购物车数据表
        $shopCartDb = Db::name('shop_cart');
        foreach ($orderDetails as $value) {
            // 多规格商品处理
            if (!empty($value['spec_value_id'])) {
                if (in_array($value['product_id'], $product_ids) && in_array($value['spec_value_id'], $spec_value_ids)) {
                    unset($value);
                }
            } 
            // 单规格商品处理
            else {
                if (in_array($value['product_id'], $product_ids)) {
                    unset($value);
                }
            }

            // 加入购物车数据
            if (!empty($value)) {
                // 查询条件
                $where = [
                    'users_id' => intval($value['users_id']),
                    'product_id' => intval($value['product_id'])
                ];
                // 规格ID是否存在
                if (!empty($value['spec_value_id'])) $where['spec_value_id'] = strval($value['spec_value_id']);
                // 查询购物车是否存在该商品
                $cartID = $shopCartDb->where($where)->getField('cart_id');
                if (!empty($cartID)) {
                    $saveData[] = [
                        'cart_id' => $cartID,
                        'product_num' => Db::raw('product_num+' . ($value['product_num'])),
                        'selected' => 1,
                        'update_time' => $times
                    ];
                } else {
                    $saveData[] = [
                        'users_id' => intval($this->users_id),
                        'product_id' => intval($value['product_id']),
                        'product_num' => intval($value['product_num']),
                        'spec_value_id' => $value['spec_value_id'],
                        'selected' => 1,
                        'add_time' => $times,
                        'update_time' => $times,
                    ];
                }
            }
        }

        if (!empty($saveData)) model('ShopCart')->saveAll($saveData);
        $this->success('操作成功', null, ['abnormal'=>0]);
    }

    // 删除订单
    public function deleteOrder($param = [])
    {
        $where = [
            'users_id' => intval($this->users_id),
            'order_id' => intval($param['order_id'])
        ];
        $deleteID = Db::name('shop_order')->where($where)->delete(true);
        if (!empty($deleteID)) {
            // 同步删除订单附表数据
            Db::name('shop_order_details')->where($where)->delete(true);
            // 同步删除订单维权数据
            Db::name('shop_order_service')->where($where)->delete(true);

            $where = [
                'order_id' => intval($param['order_id'])
            ];
            // 同步删除订单操作记录
            Db::name('shop_order_log')->where($where)->delete(true);
            // 同步删除订单维权记录
            Db::name('shop_order_service_log')->where($where)->delete(true);
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}